#!/usr/bin/env python
# -*- coding: utf-8 -*-
#code:utf-8
#
# Copyright(C) 2011 SupDo.com
# Licensed under the GUN License, Version 3.0 (the "License");
# 
# File:          articleView.py
# Author:      KuKei
# Create Date: 2011-10-13
# Description: 文章管理视图
# Modify Date: 2011-10-13

from sd.cms.views import BaseView
from sd.cms.lib.decorator import powerLevel, cachePage
from sd.cms.lib import Params, Pager
from sd.cms.lib.html import truncHtml
from sd.cms.models.paramModel import Catalog
from sd.cms.forms.appForm import ArticleForm, ArticleCmtForm
from sd.cms.models.appModel import Article, ArticleContent, ArticleCmt
import datetime, cgi
from django.db import transaction

class ArticleView(BaseView): 
    @powerLevel(Params.ADMINISTRATOR)
    @transaction.commit_on_success 
    def add(self, **args):
        articleForm = ArticleForm()
        if self.request.POST:
            articleForm = ArticleForm(self)
            if articleForm.is_valid():
                articleData = articleForm.cleaned_data
                articleData['author'] = self.power['user'].id
                articleData['crtdate'] = datetime.datetime.now()
                articleData['readcnt'] = 0
                articleContent = ArticleContent()
                articleContent.content = articleData['contentF']
                articleContent.save()
                articleModel = Article().initData(articleData)
                articleModel.summary = truncHtml(articleData['contentF'], 
                                                 self.globalinfo.sumlength if self.globalinfo.sumlength else 200)
                articleModel.content = articleContent
                articleModel.catalog = articleData['catalog']
                articleModel.save()
                self.mc.flushNS2(self.params.ARTICLELIST)
                toUrl = 'article/'+str(articleModel.name)+'.html' if articleModel.name else 'article-'+str(articleModel.id)+'.html'
                return self.redirect(toUrl)
            else:
                self.result.msg = articleForm.GetErrors()
        self.viewData['articleForm'] = articleForm
        return self.render('/addArticle.html')
    
    @powerLevel(Params.ADMINISTRATOR)
    @transaction.commit_on_success 
    def edit(self, **args):
        articleForm = ArticleForm()
        if self.request.POST:
            articleForm = ArticleForm(self)
            if articleForm.is_valid():
                articleData = articleForm.cleaned_data
                objId = int(self.request.POST['_id'])
                if objId > -1:
                    articleModel = Article.objects.get(id=int(objId))
                    articleData['crtdate'] = datetime.datetime.now()
                    articleModel = articleModel.updateData(articleData)
                    articleModel.moddate = datetime.datetime.now()
                    articleModel.summary = truncHtml(articleData['contentF'], 
                                                     self.globalinfo.sumlength if self.globalinfo.sumlength else 200)
                    articleContent = ArticleContent.objects.get(id=articleModel.content.id)
                    articleContent.content = articleData['contentF']
                    articleContent.save()
                    articleModel.content = articleContent
                    articleModel.save()
                    self.mc.flushPage(Params.ARTICLE, articleModel.id)
                    self.mc.flushNS2(self.params.ARTICLELIST)
                self.mc.flushNS2(self.params.ARTICLELIST)
                toUrl = 'article/'+str(articleModel.name)+'.html' if articleModel.name else 'article-'+str(articleModel.id)+'.html'
                return self.redirect(toUrl)
            else:
                self.result.msg = articleForm.GetErrors()
        self.viewData['articleForm'] = articleForm
        return self.render('/addArticle.html')
    
    @powerLevel(Params.ADMINISTRATOR)
    def delete(self, **args):
        if self.request.POST:
            articleModel = Article.objects.get(id=int(args['id']))
            articleModel.content.delete()
            self.mc.flushPage(Params.ARTICLE, articleModel.id)
            self.mc.flushNS2(self.params.ARTICLELIST)
            
            if self.request.POST.has_key('_retType') and self.request.POST['_retType'] == 'json':
                self.result.flag = True
                self.result.msg = "删除成功！"
                return self.render_json()
            else:
                return self.render('/listArticle.html')
            
    def addCmt(self, **args):
        commentForm = ArticleCmtForm()
        if self.request.POST:
            commentForm = ArticleCmtForm(self)
            if commentForm.is_valid():
                commentData = commentForm.cleaned_data
                objId = args['id'] if args.has_key('id') and args['id'] else -1
                if int(objId) > -1:
                    commentData['date'] = datetime.datetime.now()
                    commentData['article_id'] = objId
                    commentModel = ArticleCmt().initData(commentData)
                    commentModel.save()
                    self.mc.flushPage(Params.ARTICLE, objId)
                    if self.params.SAFECODE in self.request.session:
                        self.request.session.pop(self.params.SAFECODE)
                    self.result.flag = True
                    self.result.msg = '发布成功！'
                    self.viewData = {'id':commentModel.id, 'class':'reply' if commentModel.pid>-1 else '', 'author':commentModel.author, 'theme':self.params.DEFAULTTHEME, 'homepage':commentModel.homepage, 'date':commentModel.date.strftime('%Y-%m-%d %H:%M:%S'), 'content':cgi.escape(commentModel.content)}
                    renderHtml = self.render('/snippet/comment.html')
                    self.result.html = renderHtml._container[0]
                else:
                    self.result.flag = False
                    self.result.msg = '文章ID未可知！'
            else:
                self.result.flag = False
                self.result.msg = commentForm.GetErrors()
        return self.render_json()
    
    @powerLevel(Params.ADMINISTRATOR)
    def delCmt(self, **args):
        if self.request.POST:
            articleCmtModel = ArticleCmt.objects.get(id=int(args['id'])).delete()
            #articleCmtModel.delete()
            self.mc.flushPage(Params.ARTICLE, articleCmtModel.article_id)
            self.result.flag = True
            self.result.msg = "删除成功！"
        else:
            self.result.flag = False
            self.result.msg = "删除失败！"
        return self.render_json()

    @powerLevel(Params.ADMINISTRATOR)
    def addView(self, **args):
        articleForm = ArticleForm()
        articleForm.initOptions('catalog', Catalog.objects.toOptionsByModel('Article', 20, ('', '请选择')))
        self.result.msg = '';
        self.viewData['articleForm'] = articleForm
        return self.render('/addArticle.html')
    
    @powerLevel(Params.ADMINISTRATOR)
    def editView(self, **args):
        article = Article.objects.get(id=int(args['id']))
        articleForm = ArticleForm(self,modelData=article)
        articleForm.initOptions('catalog', Catalog.objects.toOptionsByModel('Article', 20, ('', '请选择')))
        articleForm.initDic['contentF'] = article.content.content
        self.viewData['articleForm'] = articleForm
        return self.render('/addArticle.html')
    
    @cachePage(key=Params.ARTICLELIST)
    def listView(self, **args):
        articleList = None
        catalog = None
        pager = Pager(self.request, 'atc')
        if args.has_key('field') and args['field']:
            catalog = self.getCatalog()[1][args['field']]
            pager.totalSize = Article.objects.filter(catalog=catalog, status__in=[1,2]).count()
            articleList = list(Article.objects.filter(catalog=catalog, status__in=[1,2]).order_by('-crtdate')[pager.startSize:pager.getEndSize()])
        else:
            pager.totalSize = Article.objects.filter(status__in=[1,2]).order_by('-crtdate').count()
            articleList = list(Article.objects.filter(status__in=[1,2]).order_by('-crtdate')[pager.startSize:pager.getEndSize()])
        self.viewData['articleList'] = articleList
        self.viewData['pager'] = pager.getPageList()
        self.viewData['lctList'] = self.getLocationLists(catalog)
        return self.render('/listArticle.html')
    
    @powerLevel(Params.ADMINISTRATOR)
    def listAllView(self, **args):
        pager = Pager(self.request, 'atc')
        pager.totalSize = Article.objects.all().count()
        articleList = list(Article.objects.all().order_by('-crtdate')[pager.startSize:pager.getEndSize()])
        catalogDict = self.getCatalog()[2]
        for i in range(0, len(articleList)):
            articleList[i].catalog = catalogDict[articleList[i].catalog_id]
        self.viewData['articleList'] = articleList
        self.viewData['pager'] = pager.getPageList()
        return self.render('/admin/listAllArticle.html')
    
    @cachePage(key=Params.ARTICLE)
    def view(self, **args):
        article = None
        if args.has_key('id') and args['id']:
            article = Article.objects.get(id=int(args['id']))
        else:
            article = Article.objects.get(name=args['name'])
        article.readcnt = article.readcnt+1
        article.save()
        pager = Pager(self.request, 'cmt')
        pager.totalSize = article.articlecmt_set.all().count()
        cmtList = list(article.articlecmt_set.filter(pid=-1).order_by('date')[pager.startSize:pager.getEndSize()])
        idList = [cmt.id for cmt in cmtList]
        cmtList2 = list(article.articlecmt_set.filter(pid__in=idList).order_by('date'))
        self.viewData['cmtList'] = cmtList
        self.viewData['cmtList2'] = cmtList2
        self.viewData['cmtForm'] = ArticleCmtForm()
        self.viewData['pager'] = pager.getPageList()
        self.viewData['article'] = article
        self.viewData['lctList'] = self.getLocationLists(article.catalog, article.title)
        return self.render('/article.html')
    
def action(request, **args):
    return apply(ArticleView(request).action, (), args)